package org.example.covid.daily;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.example.covid.entity.CovidCountEntity;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;

public class DailyIncrementApp {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {

        if (args.length < 2) {
            System.err.println("Usage: dailyincrement <in> <out>");
            System.exit(2);
        }
        //1、获取job
        //创建Hadoop配置对象，使用默认配置
        Configuration conf = new Configuration();
//        conf.set("mapreduce.framework.name", "local");
        //创建一个MR作业，取名叫做word count，名字可用于管理作业
        Job job = Job.getInstance(conf, DailyIncrementApp.class.getSimpleName());
        //2、设置jar包路径
        //告诉job可以跟据App这个类的元数据信息找到MR的jar文件
        job.setJarByClass(DailyIncrementApp.class);

        //3、关联mapper和reducer
        //将Mapper类加入job
        job.setMapperClass(MyMapper.class);
        //将Reducer类加入job
        job.setReducerClass(MyReducer.class);

        //4、设置最终输出的k,v类型
        //设置mapper阶段输出的key value 类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(CovidCountEntity.class);
        //设置MR最终输出的数据的Key类型,Value类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(CovidCountEntity.class);


        //设置Reducer数量
        //>=2会出现分区
        job.setNumReduceTasks(1);
//        job.setPartitionerClass(StatePartitioner.class);

        //6、设置输入输出路径
        //设置输入数据从哪个目录正的文件中读
        FileInputFormat.addInputPath(job, new Path(args[0]));
        //设置输出数据存放的文件在哪个目录下
        Path output = new Path(args[1]);
        FileSystem fs = FileSystem.get(conf);
        if (fs.exists(output)) {
            fs.delete(output, true);
        }
        FileOutputFormat.setOutputPath(job, output);

        //7、提交job
        //执行job并等待其结束，然后程序退出
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }

    public static class MyMapper extends Mapper<LongWritable, Text, Text, CovidCountEntity> {

        private Text outKey = new Text();
        private CovidCountEntity outValue = new CovidCountEntity();
        private Calendar calendar = new GregorianCalendar();

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] fileds = value.toString().split("\t");
            int n = fileds.length;
            outKey.set(fileds[0]);
            outValue.setCases(Long.parseLong(fileds[n - 2]));
            outValue.setDeaths(Long.parseLong(fileds[n - 1]));
            context.write(outKey, outValue);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date = simpleDateFormat.parse(fileds[0]);
                calendar.setTime(date);
                calendar.add(calendar.DATE, 1);
                Date newDate = calendar.getTime();
                outKey.set(simpleDateFormat.format(newDate));
                context.write(outKey, outValue);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    public static class MyReducer extends Reducer<Text, CovidCountEntity, Text, CovidCountEntity> {
        private CovidCountEntity outValue = new CovidCountEntity();

        @Override
        protected void reduce(Text key, Iterable<CovidCountEntity> values, Context context) throws IOException, InterruptedException {
            //统计变量
            final Iterator<CovidCountEntity> covidCountEntityIterator = values.iterator();
            CovidCountEntity covidCountEntity = covidCountEntityIterator.next();
            long totalCases = covidCountEntity.getCases();
            long totalDeaths = covidCountEntity.getDeaths();
            if( covidCountEntityIterator.hasNext()){
                covidCountEntity = covidCountEntityIterator.next();
                totalCases -= covidCountEntity.getCases();
                totalDeaths -= covidCountEntity.getDeaths();
                outValue.set(Math.abs(totalCases),Math.abs(totalDeaths));
                context.write(key,outValue);
            }
        }
    }
}
